//
//  ViewController.m
//  MCBLESDK
//
//  Created by Jany on 2017/11/29.
//  Copyright © 2017年 MillionConcept. All rights reserved.
//

#import "ViewController.h"
#import "MCBLE.framework/Headers/MCBLEManager.h"
#import "APIListViewController.h"
#import "MyTableViewCell.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    NSMutableArray *peripheralDataArray;
    BOOL _flag;
}
#pragma mark==================================属性==================================
@property (nonatomic, strong) NSMutableDictionary *heightAtIndexPath;//缓存高度所用字典
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *services;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet UIView *bottomBackView;
@property (nonatomic, strong) CBPeripheral *myp;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _bottomBackView.layer.shadowColor = [UIColor blackColor].CGColor;
    _bottomBackView.layer.shadowOffset = CGSizeMake(0,-1);
    _bottomBackView.layer.shadowRadius = 4;
    _bottomBackView.layer.shadowOpacity = 0.8f;
    //初始化外设数组
    peripheralDataArray = [[NSMutableArray alloc]init];
    _heightAtIndexPath = [[NSMutableDictionary alloc] init];
    
    UIView *lineView = [[UIView alloc] init];
    _myTableView.tableFooterView = lineView;
    __weak typeof(self) weakSelf = self;
    //初始化蓝牙库
    [[MCBLEManager shareMCBluetooth] setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {

        if (weakSelf.name.text.length > 0) {

            if ([peripheral.name isEqualToString:weakSelf.name.text]) {//根据名字来过滤外设
                [weakSelf insertTableView:peripheral advertisementData:advertisementData RSSI:RSSI];
            }

        }else{

            [weakSelf insertTableView:peripheral advertisementData:advertisementData RSSI:RSSI];
        }

    }];

    [self scan];
    
    _flag = YES;

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (!_flag) {
        
        _flag = YES;
        [textField resignFirstResponder];
        
        CGRect rect = _backView.frame;
        
        [UIView animateWithDuration:1.f delay:0.f usingSpringWithDamping:0.5f initialSpringVelocity:0.f options:UIViewAnimationOptionLayoutSubviews animations:^{
            
            _backView.frame = CGRectOffset(rect, 0.0, 150.0);
        } completion:^(BOOL finished) {
            
        }];
    }
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if (_flag) {
        
        _flag = NO;
        CGRect rect = _backView.frame;
        
        [UIView animateWithDuration:1.f delay:0.f usingSpringWithDamping:0.5f initialSpringVelocity:0.f options:UIViewAnimationOptionLayoutSubviews animations:^{
            
            _backView.frame = CGRectOffset(rect, 0.0, - 150.0);
        } completion:^(BOOL finished) {
            
        }];
    }
}

- (void)scan{
    [[MCBLEManager shareMCBluetooth] scanPeripherals];
}

- (void)delete{
    [peripheralDataArray removeAllObjects];
    [_myTableView reloadData];
}
- (IBAction)scanAgain:(id)sender {
    
    [peripheralDataArray removeAllObjects];
    [_myTableView reloadData];
    
    [self scan];
}

#pragma mark -UIViewController 方法
//插入table数据
-(void)insertTableView:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    
    NSArray *peripherals = [peripheralDataArray valueForKey:@"peripheral"];
    if(![peripherals containsObject:peripheral]) {
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:peripherals.count inSection:0];
        [indexPaths addObject:indexPath];
        
        NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
        [item setValue:peripheral forKey:@"peripheral"];
        [item setValue:RSSI forKey:@"RSSI"];
        [item setValue:advertisementData forKey:@"advertisementData"];
        
        NSString *macString = nil;
        NSInteger version = 0;
        NSData *mac = advertisementData[CBAdvertisementDataServiceDataKey][[CBUUID UUIDWithString:@"FF00"]];
        
        if(mac.length == 6){
            
            Byte *b = (Byte *)mac.bytes;
            macString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", b[5], b[4], b[3], b[2], b[1], b[0]];
            
        }else if(mac.length == 2){
            
            Byte *b = (Byte *)mac.bytes;
            version = b[0] * 1000 + b[1];
            
        }else if(mac.length == 9){
            
            Byte *b = (Byte *)mac.bytes;
            version = b[7] * 1000 + b[8];
            macString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", b[5], b[4], b[3], b[2], b[1], b[0]];
            
        }
        
        [item setValue:macString forKey:@"macString"];
        [peripheralDataArray addObject:item];
        
        [self.myTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }else{
        
        NSInteger index = [peripherals indexOfObject:peripheral];
        NSDictionary *item = [peripheralDataArray objectAtIndex:index];
        [item setValue:RSSI forKey:@"RSSI"];
        
        [self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:index inSection:0],nil] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark==================================tableView代理方法==================================
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return peripheralDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MyTableViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:@"cell"];
    NSDictionary *item = [peripheralDataArray objectAtIndex:indexPath.row];
    CBPeripheral *peripheral = [item objectForKey:@"peripheral"];
    NSDictionary *advertisementData = [item objectForKey:@"advertisementData"];
    NSNumber *RSSI = [item objectForKey:@"RSSI"];
    
    if (!cell) {
        cell = [[MyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //peripheral的显示名称,优先用kCBAdvDataLocalName的定义，若没有再使用peripheral name
    NSString *peripheralName;
    if ([advertisementData objectForKey:@"kCBAdvDataLocalName"]) {
        peripheralName = [NSString stringWithFormat:@"%@",[advertisementData objectForKey:@"kCBAdvDataLocalName"]];
    }else if(!([peripheral.name isEqualToString:@""] || peripheral.name == nil)){
        peripheralName = peripheral.name;
    }else{
        peripheralName = [peripheral.identifier UUIDString];
    }
    
    if ([RSSI integerValue] < -90) {

        cell.headImageView.image = [UIImage imageNamed:@"Signal_0"];
        
    } else if ([RSSI integerValue] < -70) {

        cell.headImageView.image = [UIImage imageNamed:@"Signal_1"];
        
    } else if ([RSSI integerValue] < -50) {

        cell.headImageView.image = [UIImage imageNamed:@"Signal_2"];
        
    } else {
        
        cell.headImageView.image = [UIImage imageNamed:@"Signal_3"];
    }
    
    cell.nameTitleLabel.text = peripheralName;
    
    if (![item objectForKey:@"macString"] && [RSSI integerValue] == 0) {
        cell.detailLabel.text = @"已经连接过的设备";
    }else if(![item objectForKey:@"macString"]){
        cell.detailLabel.text = @"没有广播mac地址";
    }else{
        cell.detailLabel.text = [item objectForKey:@"macString"];
    }

    //信号和服务
    cell.rissLabel.text = [NSString stringWithFormat:@"RSSI:%@",RSSI];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_flag) {
        
        [[MCBLEManager shareMCBluetooth] cancelScan];//ControlViewController
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *item = [peripheralDataArray objectAtIndex:indexPath.row];
        CBPeripheral *peripheral = [item objectForKey:@"peripheral"];
        _myp = peripheral;
        //__weak typeof (self)weakSelf = self;
        [[MCBLEManager shareMCBluetooth] connectToPeripheral:peripheral];
        [self performSegueWithIdentifier:@"FunctionView" sender:[MCBLEManager shareMCBluetooth]->connectedPeripheral];

    }else{
        
        //取消键盘
        [_name resignFirstResponder];
        [_services resignFirstResponder];
        
        _flag = YES;
        CGRect rect = _backView.frame;
        
        [UIView animateWithDuration:1.f delay:0.f usingSpringWithDamping:0.5f initialSpringVelocity:0.f options:UIViewAnimationOptionLayoutSubviews animations:^{
            _backView.frame = CGRectOffset(rect, 0.0, 150.0);
        } completion:^(BOOL finished) {
            
        }];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSNumber *height = @(cell.frame.size.height);
    [self.heightAtIndexPath setObject:height forKey:indexPath];
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSNumber *height = [self.heightAtIndexPath objectForKey:indexPath];
    if(height){
        return height.floatValue;
    }else{
        return 60;
    }
}



- (void)viewWillAppear:(BOOL)animated{
    if (_myp) {
        [[MCBLEManager shareMCBluetooth] cancelPeripheralConnection:_myp];
    }
}
@end
